<template>
  <div class="patient-detail-container">
    <!-- 顶部信息区域 -->
    <div class="patient-header bg-primary">
      <van-nav-bar
        title="患者详情"
        left-arrow
        @click-left="onClickLeft"
        class="transparent-nav-bar"
      >
        <template #right>
          <van-icon name="share-o" size="18" color="white" @click="onClickShare" />
        </template>
      </van-nav-bar>
      
      <div class="patient-info">
        <div class="patient-avatar">
          <img :src="getAvatarByGender(patientInfo.gender)" alt="头像">
        </div>
        <div class="patient-basic-info">
          <!-- 显示骨架屏或实际内容 -->
          <template v-if="isLoading">
            <div class="skeleton-line skeleton-title"></div>
            <div class="skeleton-line"></div>
            <div class="skeleton-line"></div>
            <div class="skeleton-line"></div>
          </template>
          <template v-else>
            <div class="patient-name">
              {{ patientInfo.name || '未知' }}
              <span class="patient-gender">{{ patientInfo.gender === 1 ? '男' : patientInfo.gender === 2 ? '女' : '' }}</span>
              <span class="patient-age">{{ calculateAge(patientInfo) }}岁</span>
            </div>
            <div class="patient-diagnosis">诊断: {{ diagnosisInfo || '暂无' }}</div>
            <div class="patient-department">科室: {{ visitInfo.departmentName || '暂无' }}</div>
            <div class="patient-visit-time">就诊时间: {{ formatDate(visitInfo.visitTime) }}</div>
          </template>
        </div>
      </div>
    </div>
    
    <!-- 标签页 -->
    <van-tabs v-model:active="activeTab" swipeable sticky animated :swipe-threshold="5">
      <van-tab title="患者信息">
        <patient-info-tab 
          :patient-id="patientId" 
          :patient-info="patientInfo" 
          :visit-info="visitInfo" 
          :vital-signs="vitalSigns"
          :recent-vital-signs="recentVitalSigns"
          :is-loading="isLoading"
        />
      </van-tab>
      
      <van-tab title="检查">
        <medical-order-tab 
          :visit-id="visitId" 
          :order-type="2" 
          tab-name="检查"
        />
      </van-tab>
      
      <van-tab title="检验">
        <medical-order-tab 
          :visit-id="visitId" 
          :order-type="3" 
          tab-name="检验"
        />
      </van-tab>
      
      <van-tab title="药品">
        <medical-order-tab 
          :visit-id="visitId" 
          :order-type="1" 
          tab-name="药品"
        />
      </van-tab>
      
      <van-tab title="手术">
        <medical-order-tab 
          :visit-id="visitId" 
          :order-type="4" 
          tab-name="手术"
        />
      </van-tab>
      
      <van-tab title="治疗">
        <medical-order-tab 
          :visit-id="visitId" 
          :order-type="5" 
          tab-name="治疗"
        />
      </van-tab>
      
      <van-tab title="病历">
        <medical-record-tab :visit-id="visitId" />
      </van-tab>
    </van-tabs>

    <!-- 加载状态指示器 -->
    <van-overlay :show="isLoading" z-index="9999" class="loading-overlay">
      <van-loading color="#1989fa" size="36px">加载中...</van-loading>
    </van-overlay>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { 
  getPatientDetail, 
  getVisitDetail, 
  getPatientVitalSigns, 
  getRecentPatientVitalSigns 
} from '@/api/patient';
import PatientInfoTab from '@/components/PatientInfoTab.vue';
import MedicalOrderTab from '@/components/MedicalOrderTab.vue';
import MedicalRecordTab from '@/components/MedicalRecordTab.vue';

const router = useRouter();
const route = useRoute();

// 获取路由参数
const patientId = ref(route.params.patientId);
const visitId = ref(route.params.visitId);

// 标签页选中状态
const activeTab = ref(0);

// 加载状态
const isLoading = ref(true);

// 患者基本信息
const patientInfo = ref({});
const visitInfo = ref({});
const vitalSigns = ref({});
const recentVitalSigns = ref([]);
const diagnosisInfo = ref('');

// 获取患者基本信息
const fetchPatientInfo = async () => {
  try {
    const res = await getPatientDetail(patientId.value);
    if (res.data) {
      patientInfo.value = res.data;
    }
  } catch (error) {
    console.error('获取患者信息失败', error);
    showToast('获取患者信息失败');
  }
};

// 获取就诊信息
const fetchVisitInfo = async () => {
  try {
    const res = await getVisitDetail(visitId.value);
    if (res.data) {
      visitInfo.value = res.data;
      
      // 临时展示诊断信息，实际应该从诊断信息接口获取
      diagnosisInfo.value = res.data.chiefComplaint || '暂无诊断信息';
    }
  } catch (error) {
    console.error('获取就诊信息失败', error);
    showToast('获取就诊信息失败');
  }
};

// 获取生命体征信息
const fetchVitalSigns = async () => {
  try {
    const res = await getPatientVitalSigns(patientId.value);
    if (res.data) {
      vitalSigns.value = res.data;
    }
  } catch (error) {
    console.error('获取生命体征失败', error);
  }
};

// 获取近7条生命体征
const fetchRecentVitalSigns = async () => {
  try {
    const res = await getRecentPatientVitalSigns(patientId.value);
    if (res.data) {
      recentVitalSigns.value = res.data;
    }
  } catch (error) {
    console.error('获取近7条生命体征失败', error);
  }
};

// 根据性别获取头像
const getAvatarByGender = (gender) => {
  return gender === 1 
    ? 'https://img01.yzcdn.cn/vant/cat.jpeg' 
    : 'https://img01.yzcdn.cn/vant/dog.jpeg';
};

// 计算年龄
const calculateAge = (patient) => {
  if (!patient.birthDate) return '';
  
  try {
    const birthYear = parseInt(patient.birthDate.substring(0, 4));
    const currentYear = new Date().getFullYear();
    return currentYear - birthYear;
  } catch (e) {
    return '';
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (e) {
    return dateStr;
  }
};

// 返回上一页
const onClickLeft = () => {
  router.back();
};

// 分享功能
const onClickShare = () => {
  showToast('分享功能开发中');
};

// 页面加载时获取数据
onMounted(async () => {
  isLoading.value = true;
  try {
    await Promise.all([
      fetchPatientInfo(),
      fetchVisitInfo(),
      fetchVitalSigns(),
      fetchRecentVitalSigns()
    ]);
  } catch (error) {
    console.error('获取患者数据失败', error);
  } finally {
    isLoading.value = false;
  }
});
</script>

<style scoped>
.patient-detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.patient-header {
  color: white;
  padding-bottom: 16px;
}

.bg-primary {
  background-color: #1989fa;
}

.transparent-nav-bar {
  background-color: transparent;
  color: white;
}

.patient-info {
  display: flex;
  padding: 0 16px;
}

.patient-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  border: 2px solid rgba(255, 255, 255, 0.5);
}

.patient-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.patient-basic-info {
  flex: 1;
}

.patient-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.patient-gender, .patient-age {
  font-size: 14px;
  margin-left: 8px;
  font-weight: normal;
}

.patient-diagnosis, .patient-department, .patient-visit-time {
  font-size: 14px;
  margin-top: 2px;
  opacity: 0.9;
}

:deep(.van-tabs__wrap) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.van-tab) {
  font-size: 14px;
}

/* 骨架屏样式 */
.skeleton-line {
  height: 16px;
  margin-bottom: 8px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
}

.skeleton-title {
  width: 40%;
  height: 20px;
}

.skeleton-line:nth-child(2) {
  width: 60%;
}

.skeleton-line:nth-child(3) {
  width: 50%;
}

.skeleton-line:nth-child(4) {
  width: 80%;
  margin-bottom: 0;
}

.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 